package com.lagou.rpc.consumer.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;

/**
 * 客户端处理类
 * 1.继承SimpleChannelInboundHandler处理消息的入站
 * 2。发送消息，实现Callable接口达到异步接收响应的效果
 * 3。接收消息
 *
 */
@Component
@ChannelHandler.Sharable
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    private ChannelHandlerContext ctx;
    //发送的消息
    private String requestMsg;
    //服务端响应的消息
    private String responseMsg;

    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx = ctx;
    }

    /**
     * 通道读取就绪事件
     * @param channelHandlerContext
     * @param msg
     * @throws Exception
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        responseMsg = msg;
        //消息读取完毕后唤醒等待的线程
        notify();
    }

    /**
     * 发送消息到客户端
     * @return
     * @throws Exception
     */
    @Override
    public synchronized Object call() throws Exception {
        //发送消息
        ctx.writeAndFlush(requestMsg);
        //发送消息后，线程处于等待状态
        wait();
        return responseMsg;
    }
}
